/* 首先解决click事件300ms延迟的问题 */
FastClick.attach(document.body);
// 获取第一个轮播图内容
let swiperOne = document.querySelector(".container_1 .mySwiperOne .swiper-wrapper"),
  // 获取第一个轮播图背景
  swiperOne_bg = document.querySelector(".container_1 .bg .swiper-wrapper"),
  // 获取第二个轮播图
  swiperTwo = document.querySelector(".container_1 .mySwiperTwo .swiper-wrapper"),
  // 获取热门推荐
  recommend = document.querySelector('.container_1 .main .main_left .l_hot_recommend .wrap'),
  // 获取榜单
  musicList = document.querySelectorAll('.container_1 .main .main_left .l_music_list_wrap ol');
//获取播放器
const myPlayer = document.querySelector('.myplayer'),
  play_control = document.querySelector('.myplayer .btns'),
  audioBox = document.querySelector('#audioBox'),
  alreadyBox = document.querySelector('.cur'),
  currentBox = document.querySelector('.mus_tim em'),
  durationBox = document.qu bar_music = document.querySelector('.cur span'),
  bar_vol = document.querySelector(".vol_line .btn");

//绑定数据
const render = function render(data) {
  let str_1 = ``,
    str_1_bg = ``;
  data[0].swiper1.forEach((item) => {
    let { id, pic, background } = item;
    str_1 += `<div class="swiper-slide">
    <img src="${pic}"erySelector('.mus_tim span');
let timer = null,
 
      alt="">
  </div>`
    str_1_bg += `<div class="swiper-slide">
    <img src="${background}"  alt="">
      </div>`

  })
  swiperOne.innerHTML = str_1;
  swiperOne_bg.innerHTML = str_1_bg;

  var Swiper1_bg = new Swiper('.mySwiperOnebg', {
    effect: 'fade',
    loop: true,
  });
  var swiper1 = new Swiper(".mySwiperOne", {
    //双向控制
    controller: {
      control: Swiper1_bg,
    },
    autoplay: true,
    loop: true,
    effect: 'fade',
    navigation: {
      nextEl: ".next",
      prevEl: ".prev",
    },
    pagination: {
      el: ".pag",
      clickable: true,
      bulletClass: 'my-bullet',//需设置.my-bullet样式
      bulletActiveClass: 'my-bullet-active',
    },
    observer: true,//修改swiper自己或子元素时，自动初始化swiper
    observeParents: true,//修改swiper的父元素时，自动初始化swiper
  });

  let str_2 = ``;
  data[1].swiper2.forEach((item) => {
    let { id, pic, title, creator } = item;
    str_2 += `<div class="swiper-slide">
    <img src="${pic}"
      alt="">
    <a class="msk" href=""></a>
    <a class="ply" href=""></a>
    <p class="tit1"><a href="">${title}</a></p>
    <p class="tit2"><a href="">${creator}</a></p>
  </div>`;
  });
  swiperTwo.innerHTML = str_2;

  var swiper2 = new Swiper(".mySwiperTwo", {
    slidesPerView: 5,
    spaceBetween: 11,
    slidesPerGroup: 5,
    loop: true,
    loopFillGroupWithBlank: true,
    navigation: {
      nextEl: ".next1",
      prevEl: ".prev1",
    },
    observer: true,//修改swiper自己或子元素时，自动初始化swiper
    observeParents: true,//修改swiper的父元素时，自动初始化swiper
  });

  let str_3 = ``;
  data[2].recommend.forEach((item) => {
    let { id, pic, nb, tit, i } = item;
    str_3 += `<li>
    <div class="img">
      <img src="${pic}"
        alt="">
      <a class="eff" href=""></a>
      <div class="btm">
        <a href=""></a>
        <span class="icon-headset"></span>
        <span class="nb">${nb}</span>
      </div>
    </div>
    <p><a href="">${i}${tit}</a></p>
  </li>`;
  });
  recommend.innerHTML = str_3;

  let str_4 = ``;
  data[3].forEach((item, index) => {
    let { music } = item;
    str_4 += ` <li>
                    <span>${index + 1}</span>
                    <a href="">${music}</a>
                    <div class="oper">
                      <a class="oper_1" href=""></a>
                      <a class="oper_2" href=""></a>
                      <a class="oper_3" href=""></a>
                    </div>
                  </li>
                `;

  });
  musicList[0].innerHTML = str_4;
  musicList[1].innerHTML = str_4;
  musicList[2].innerHTML = str_4;
};

//功能实现
const handle = function handle() {
  //返回顶部按钮
  let html = document.documentElement || document.body,
    back = document.querySelector('.bottom .back');
  window.onscroll = function () {
    if (html.scrollTop > 100) {//滚动距离大于100 按钮显示
      back.style.opacity = 1;
      back.style.zIndex = 999;
    } else {
      back.style.opacity = 0;
      back.style.zIndex = -10;
    }
  }
  //底部音乐播放器
  let ctrlBox = document.querySelector('.myplayer .ctrl'),
    vol = document.querySelector('.vol'),
    loopTip = document.querySelector('.loop_tip'),
    ste = 0;
  //音量及播放方式部分
  bar_vol.onmousedown = function (ev) {
    this.startY = ev.clientY;
    this.startH = document.querySelector('.curr').offsetHeight;
    this.MOVE = volMove.bind(this);
    this.UP = volUp.bind(this);
    window.addEventListener('mousemove', this.MOVE);
    window.addEventListener('mouseup', this.UP);
  }
  ctrlBox.addEventListener('click', (ev) => {
    //音量点击出现消失
    if (ev.target.className === 'icn_vol') {
      if (ste === 0) {
        vol.style.display = 'block';
        ste = 1;
      } else {
        vol.style.display = 'none';
        ste = 0;
      }
    }
    //点击切换播放方式
    if (ev.target.classList.contains('icn_c')) {
      loopTip.style.display = 'block';
      setTimeout(() => {
        loopTip.style.display = 'none';
      }, 1000)
    }
    if (ev.target.classList.contains('icn_loop')) {
      ev.target.classList.remove('icn_loop');
      ev.target.classList.add('icn_shuff');
      loopTip.style.display = 'block';
      loopTip.innerHTML = '随机';
      return;
    }
    if (ev.target.classList.contains('icn_shuff')) {
      ev.target.classList.remove('icn_shuff');
      ev.target.classList.add('icn_one');
      loopTip.style.display = 'block';
      loopTip.innerHTML = '单曲循环';
      return;
    }
    if (ev.target.classList.contains('icn_one')) {
      ev.target.classList.remove('icn_one');
      ev.target.classList.add('icn_loop');
      loopTip.style.display = 'block';
      loopTip.innerHTML = '循环';
      return;
    }

  });
  //添加一首音乐
  // 添加歌曲
  (function () {
    musicMethod.add("./media/合拍.m4a", "https://p1.music.126.net/Ethtz4VJFKtuuhpcd9WLzg==/109951168252754401.jpg?param=34y34", "合拍", "许嵩");
    musicMethod.add("./media/精卫.m4a", "https://p3.music.126.net/jSH_ikeooxveWl0BTc3Xkg==/109951166786983190.jpg?param=34y34", "精卫", "30年前，50年后");
    musicMethod.add("./media/若把你.m4a", "https://p4.music.126.net/M877M2-VhWZiLPVFORf9iQ==/109951163401482434.jpg?param=34y34", "若把你", "Kirsty刘瑾睿");
    musicMethod.add("./media/我记得.m4a", "https://p4.music.126.net/FCWD6ibS2JK2B3QAnXuzwQ==/109951167805892385.jpg?param=34y34", "我记得", "赵雷");
    document.querySelector('.add .icn_list').innerHTML=musicMethod.songs.length;
  })()
  //播放按钮事件绑定
  play_control.addEventListener('click', (ev) => {
    //暂停播放
    if (ev.target.classList.contains('play')) {
      //当前暂停使其播放
      if (audioBox.paused) {
        musicMethod.play(ev.target);
        ev.target.classList.add('pas');
        $sub.emit('playing');
        timer = setInterval(() => {
          $sub.emit('playing');
        }, 1000);
        return;
      } // 当前是播放的:让其暂停
      ev.target.classList.remove('pas');
      musicMethod.stop();
      clearInterval(timer);
    }
    //上一首
    if (ev.target.className === "pre") {
      musicMethod.prev();
    }
    //下一首
    if (ev.target.className === "nex") {
      musicMethod.next();
    }

  })
  //进度条拖拽
  bar_music.onmousedown = function (ev) {
    this.startX = ev.clientX;
    this.startW = alreadyBox.offsetWidth;
    this.MOVE = move.bind(this);
    this.UP = up.bind(this);
    window.addEventListener('mousemove', this.MOVE);
    window.addEventListener('mouseup', this.UP);
  }
};

//封装一个音乐播放器的方法
var musicMethod = {
  songs: [],
  index: 0,
  //播放
  play: function () {
    audioBox.src = this.songs[this.index][0];
    document.querySelector('.cov img').src = this.songs[this.index][1];
    document.querySelector('.tit_mus').innerHTML = this.songs[this.index][2];
    document.querySelector('.tit_aur').innerHTML = this.songs[this.index][3];
    audioBox.play();
  },
  //暂停
  stop: function () {
    audioBox.pause();
  },
  //添加到音乐列表
  add: function add(src, pic, song, author) {
    this.songs.push([src, pic, song, author]);
  },
  //上一首
  prev: function prev() {
    let len = this.songs.length;
    if (this.index + 1 >= 0 && this.index < len) {
      if (this.index == 0) {
        this.index = len;
      }
      this.index--;
      musicMethod.play();
    }
  },
  //下一首
  next: function next(e) {
    let len = this.songs.length;
    if (this.index + 1 >= 0 && this.index < len) {
      this.index++;
      if (this.index == len) {
        this.index = 0;
      }
      musicMethod.play();
    }
  }
}
//音量点击拖拽
const volMove = function volMove(ev) {
  let changeY = ev.clientY - this.startY;
  // resultY = this.startH + changeY;
  changeY = changeY < 0 ? 0 : (changeY > 81 ? 81 : changeY);
  // resultY = resultY < 0 ? 0 : (resultY > 81 ? 81 : resultY);
  bar_vol.style.top = `${changeY}px`;
  document.querySelector('.curr').style.height = `${(1 - (changeY / 81)) * 93}px`;
  audioBox.volume = 1 - (changeY / 81);
};
const volUp = function volUp(ev) {
  //不会跟着一直移动，第一次抬起后，就关闭抬起事件移动事件
  window.removeEventListener("mouseup", this.UP);
  window.removeEventListener("mousemove", this.MOVE);
}
//进度条点击拖拽
const move = function move(ev) {
  let changeX = ev.clientX - this.startX,
    result = this.startW + changeX;
  result = (result * 100 / 466) > 100 ? 100 : (result * 100 / 466);
  alreadyBox.style.width = `${result}%`;
};
const up = function up(ev) {
  //不会跟着一直移动，第一次抬起后，就关闭抬起事件移动事件
  window.removeEventListener("mouseup", this.UP);
  window.removeEventListener("mousemove", this.MOVE);

  let res = alreadyBox.style.width || '0';
  audioBox.currentTime = Math.floor(audioBox.duration) * (parseFloat(res) / 100);
  $sub.emit('playing');
}

//时间格式化
const formatTime = function formatTime(time) {
  let minutes = Math.floor(time / 60),
    seconds = Math.floor(time - minutes * 60);
  if (minutes < 10) minutes = "0" + minutes;
  if (seconds < 10) seconds = "0" + seconds;
  return {
    minutes,
    seconds
  }
};

//音乐播放和暂停要处理的事情
$sub.on("playing", () => {
  //控制进度条
  let currentTime = audioBox.currentTime,//播放时间
    duration = audioBox.duration;//总时间
  if (!currentTime || !duration) return;
  let ratio = (currentTime / duration).toFixed(2);
  // console.log(ratio);
  if (ratio > 1) ratio = 1;
  alreadyBox.style.width = `${ratio * 100}%`;
  //进度条时间
  let currentObj = formatTime(currentTime),
    durationObj = formatTime(duration);
  currentBox.innerHTML = `${currentObj.minutes}:${currentObj.seconds}`;
  durationBox.innerHTML = `${durationObj.minutes}:${durationObj.seconds}`;
  // 播放完毕
  if (currentTime >= duration) $sub.emit('playend');
  //控制歌词处理
  //歌词移动
});
$sub.on("playend", () => {
  //下一曲
  musicMethod.next()
});


// 基于Promise管理异步数据请求
const query = function query() {
  return new Promise(resolve => {//返回一个成功的实例
    // ajax
    let xhr = new XMLHttpRequest;
    xhr.open('GET', './data.json');
    xhr.onreadystatechange = () => {
      let { readyState, status, responseText } = xhr;
      if (readyState === 4 && status === 200) {
        let data = JSON.parse(responseText);
        resolve(data);
      }
    };
    xhr.send();
  });
};
query().then(data => {
  // console.log(data[3]);
  // 数据请求成功
  render(data);
  handle();
});